$(document).ready(function() {
  require([
    "inputdrop",
    "tree"
  ], function (inputdrop, tree) {

    var list_current_type;

    var list_current_data_name;

    var current_selected_node_id;

    var current_selected_node_name;

    var paramObj;

    event_init();

    selected_asset_list_get({
      paramObj: paramObj,
      isLoad: true,
      maskObj: "body"
    });

    $("#accordion_icon").find("div").eq(0).click();

    function event_init() {
      $("input[placeholder]").placeholder();
      $("#candidate_asset_btn").click(function() {
        candidate_asset_tem_init();
      });
      $("#delete_btn").click(function() {
        selected_asset_list_batch_delete();
      });

      $("#searchIcon").click(function() {
        key = $("#searchKey").val();
        paramObj.keyword = key;
        selected_asset_list_get({
          paramObj: paramObj,
          isLoad: true,
          maskObj: "body"
        });
      });
      $("#searchKey").keydown(function(event) {
        if (event.keyCode == 13) {
          $("#searchIcon").trigger("click");
        }
      });

    }

    function selected_asset_list_get(opt) {
      var list_url;
      var header = [
        { text: "", name: "t", width: 3, hideSearch: "hide" },
        { text: "资产名称", name: "name", width: 15, align: "left", tip:true},
        { text: "资产类型", name: "type", width: 15, align: "center",  tip:true
          // searchRender: function (el) {
          //   xd_ajax_get({
          //     url: 'api/property/type/list',
          //     isLoad: true,
          //     successCallBack: function (data) {
          //       if (data.list.length > 0) {
          //         var selectData = [];
          //         for (var i in data.list) {
          //           var text = data.list[i].name;
          //           var id = data.list[i].id;
          //           selectData.push({
          //             id: id,
          //             text: text
          //           });
          //         }

          //         g_formel.select_render(el, {
          //           data: selectData,
          //           name:'type'
          //         });
          //       }
          //     }
          //   })
          // }
        },
        { text: "管控域", name: "systemName", width: 15, align: "left" ,tip:true},
        { text: "操作系统", name: "os", width: 15, align: "left" },
        {
          text: "IP地址",
          name: "ip",
          width: 15,
          align: "left"
        },
        { text: "设备状态", name: "status", width: 15, align: "left" }

      ];

      list_url = "api/property/list";

      g_grid.render($("#table_div1"), {
        header: header,
        oper: [
          {
            icon: "rh-icon rh-edit",
            text: "编辑",
            aclick: selected_asset_list_update
          },
          {
            icon: "rh-icon rh-edit",
            text: "复用",
            aclick: selected_asset_list_reuse
          },
          {
            icon: "rh-icon rh-edit",
            aclick: selected_asset_stop,
            customRender: function(rowData) {
              return {
                text: rowData.status == '启用' ? '停用' : '启用'
              };
            }
          },
          {
            icon: "rh-icon rh-delete",
            text: "删除",
            aclick: selected_asset_list_delete
          }
        ],
        operWidth: "90px",
        url: list_url,
        type:'xd',
        dataKey: 'list',
        paramObj: opt.paramObj,
        hasBorder : false,
        hideSearch: true,
        queryBefore: function(paramObj) {
          if (list_current_data_name == "assetType") {
            paramObj.typeId = current_selected_node_id == '-1' ? '' : current_selected_node_id;
          } else {
            paramObj.systemId = current_selected_node_id == '-1' ? '' : current_selected_node_id;
          }
        },
        maskObj: opt.maskObj,
        isLoad: opt.isLoad,
        dbIndex: 1,
        autoHeight : true,
        showCount : true
      });
    }

    // 点击启用
    $('#startBtn').unbind().on('click', function () {
      var row_data = g_grid.getData($("#table_div1"),{chk:true});
      if(row_data.length == 0) {
        g_dialog.operateAlert(null, "请选择要启用的资产！", 'error');
      } else {
        var openIds = [];
        for (var i = 0; i < row_data.length; i++) {
          openIds.push({
            id: row_data[i].id,
            status: '1'
          });
        }
        g_dialog.operateConfirm("确认启用选中的记录吗?", {
          saveclick: function() {
            xd_ajax_post({
              url: "api/property/updateStatus",
              paramObj: openIds,
              isLoad: false,
              successCallBack: function(data) {
                g_dialog.operateAlert(null, "操作成功！");
                tree_get(current_selected_node_id);
              },
              failCallBack: function() {
                g_grid.refresh($("#table_div1"));
                tree_get(current_selected_node_id);
              }
            });
          }
        });
      }
    });

    // 点击停用
    $('#stopBtn').unbind().on('click', function() {
      var row_data = g_grid.getData($('#table_div1'), {chk:true});
      if(row_data.length == 0) {
        g_dialog.operateAlert(null, "请选择要停用的资产！", 'error');
      } else {
        var closeIds = [];
        for (var i = 0; i < row_data.length; i++) {
          closeIds.push({
            id: row_data[i].id,
            status: '0'
          });
        }
        g_dialog.operateConfirm("确认停用选中的记录吗?", {
          saveclick: function() {
            xd_ajax_post({
              url: "api/property/updateStatus",
              paramObj: closeIds,
              isLoad: false,
              successCallBack: function(data) {
                g_dialog.operateAlert(null, "操作成功！");
                tree_get(current_selected_node_id);
              },
              failCallBack: function() {
                g_grid.refresh($("#table_div1"));
                tree_get(current_selected_node_id);
              }
            });
          }
        });
      }
    })

    // 点击删除
    $('#deleteBtn').unbind().on('click', function() {
      var row_data = g_grid.getData($('#table_div1'), {chk:true});
      if(row_data.length == 0) {
        g_dialog.operateAlert(null, "请选择要删除的资产！", 'error');
      } else {
        var deleteIds = [];
        for (var i = 0; i < row_data.length; i++) {
          deleteIds.push(row_data[i].id);
        }
        g_dialog.operateConfirm("确认删除选中的记录么?", {
          saveclick: function() {
            xd_ajax_post({
              url: "api/property/delete",
              paramObj: deleteIds,
              successCallBack: function(data) {
                g_dialog.operateAlert(null, "操作成功！");
                tree_get(current_selected_node_id);
              },
              failCallBack: function() {
                g_grid.refresh($("#table_div1"));
                tree_get(current_selected_node_id);
              }
            });
          }
        });
      }
    })

    // 导出excel
    $('#exportExcel').unbind().on('click', function () {
      g_dialog.operateConfirm("确认导出表格中记录?", {
        saveclick: function() {
          debugger
          var paramsStr;
          if (list_current_data_name == 'assetType') {
            paramsStr = 'typeId=' + paramObj.typeId + '&keyword=' + (paramObj.keyword ? paramObj.keyword : '');
          } else {
            paramsStr = 'systemId=' + paramObj.systemId + '&keyword=' + (paramObj.keyword ? paramObj.keyword : '');
          }
          window.open('api/public/property/list/excel?' + paramsStr);
        }
      });
    })

    // 编辑
    function selected_asset_list_update(rowData) {
      $.ajax({
        type: "GET",
        url: "module/strategy/webapp_notice_tpl.html",
        success: function(data) {
          g_dialog.dialog($(data).find("[id=asset_edit_template]"), {
            width: "850px",
            init: init,
            title: "移动终端通知策略",
            saveclick: save_click
          });
        }
      });

      function init(el) {
        if (rowData) {
          $('#systemId').attr('disabled', 'true');
        }
        initSelect2Data(function () {
          laydate.render({
            elem: '#buyDate',
            format: 'yyyy-MM-dd',
            showBottom: false
          });
          xd_ajax_get({
            url: 'api/property/info',
            paramObj: {
              id: rowData.id
            },
            isLoad: true,
            maskObj: "body",
            successCallBack: function(data) {
              data.buyDate && (data.buyDate = new Date(data.buyDate).Format('yyyy-MM-dd'));
              el.umDataBind("render", data);
            }
          });
        });
      }

      function save_click(el, saveObj) {
        clearValidatorStyle($('#query_form'));
        if (!validateForm($('#query_form'))) {
          return false;
        }
        saveObj.id = rowData.id;
        saveObj.buyDate && (saveObj.buyDate = new Date(saveObj.buyDate).getTime());
        saveObj.systemId = $('#systemId').val();

        xd_ajax_get({
          url: 'api/property/checkIP',
          paramObj: {
            id: rowData.id,
            systemId: saveObj.systemId,
            ip: saveObj.ip
          },
          successCallBack: function (data) {
            if (!data) {
              // g_dialog.operateAlert(null, '同一管控域资产IP不能重复!', 'error');
              $('#ip').addClass('input_validation-failed').attr('tip', '同一管控域资产IP不能重复!');
              return false;
            } else {
              xd_ajax_get({
                url: 'api/property/checkName',
                paramObj: {
                  id: saveObj.id,
                  name: saveObj.name
                },
                successCallBack: function (data1) {
                  if (!data1) {
                    // g_dialog.operateAlert(null, '同一管控域资产IP不能重复!', 'error');
                    $('#name').addClass('input_validation-failed').attr('tip', '资产名称不能重复!');
                    return false;
                  } else {
                    xd_ajax_post({
                      url: 'api/property/save',
                      paramObj: [saveObj],
                      isLoad: true,
                      maskObj: "body",
                      successCallBack: function(data) {
                        g_dialog.operateAlert();
                        g_dialog.hide(el);
                        tree_get(current_selected_node_id);
                        selected_asset_list_get({
                          paramObj: paramObj,
                          isLoad: true,
                          maskObj: "body"
                        });
                      }
                    });
                  }
                }
            })
            }
          }
        })
      }
    }

    // 复用
    function selected_asset_list_reuse(rowData) {
      $.ajax({
        type: "GET",
        url: "module/strategy/webapp_notice_tpl.html",
        success: function(data) {
          g_dialog.dialog($(data).find("[id=asset_edit_template]"), {
            width: "850px",
            init: init,
            title: "资产信息修改",
            saveclick: save_click
          });
        }
      });

      function init(el) {
        initSelect2Data(function () {
          xd_ajax_get({
            url: 'api/property/info',
            paramObj: {
              id: rowData.id
            },
            isLoad: true,
            maskObj: "body",
            successCallBack: function(data) {
              data.name = data.name + '-复用';
              data.buyDate && (data.buyDate = new Date(data.buyDate).Format('yyyy-MM-dd'));
              el.umDataBind("render", data);
              el.find("select").trigger("change");
            }
          });
        });
      }
      function save_click(el, saveObj) {
        clearValidatorStyle($('#query_form'));
        if (!validateForm($('#query_form'))) {
          return false;
        }
        xd_ajax_get({
          url: 'api/property/checkName',
          paramObj: {
            name: saveObj.name,
          },
          successCallBack: function (data) {
            if (!data) {
              // g_dialog.operateAlert(null, '资产名称不能重复!', 'error');
              $('#name').addClass('input_validation-failed').attr('tip', '资产名称不能重复!');
              return false;
            } else {
              xd_ajax_get({
                url: 'api/property/checkIP',
                paramObj: {
                  systemId: saveObj.systemId,
                  ip: saveObj.ip
                },
                successCallBack: function (data1) {
                  if (!data1) {
                    // g_dialog.operateAlert(null, '同一管控域资产IP不能重复!', 'error');
                    $('#ip').addClass('input_validation-failed').attr('tip', '同一管控域资产IP不能重复!');
                    return false;
                  } else {
                    saveObj.buyDate && (saveObj.buyDate = new Date(saveObj.buyDate).getTime());
                    xd_ajax_post({
                      url: 'api/property/save',
                      paramObj: [saveObj],
                      isLoad: true,
                      maskObj: "body",
                      successCallBack: function(data) {
                        g_dialog.operateAlert();
                        g_dialog.hide(el);
                        tree_get(current_selected_node_id);
                        selected_asset_list_get({
                          paramObj: paramObj,
                          isLoad: true,
                          maskObj: "body"
                        });
                      }
                    });
                  }
                }
              })
            }
          }
        });
      }
    }

    // 停用
    function selected_asset_stop(rowData) {
      var stopId = rowData.id;
      g_dialog.operateConfirm('确认'+ (rowData.status == '停用' ? '启用' : '停用') +'选中的记录吗?', {
          saveclick: function() {
            xd_ajax_post({
              url: "api/property/updateStatus",
              paramObj: [{
                id: stopId,
                status: rowData.status == '停用' ? '1' : '0'
              }],
              isLoad: false,
              successCallBack: function(data) {
                g_dialog.operateAlert(null, "操作成功！");
                tree_get(current_selected_node_id);
              },
              failCallBack: function() {
                g_grid.refresh($("#table_div1"));
                tree_get(current_selected_node_id);
              }
            });
          }
        });
    }
    // 删除
    function selected_asset_list_delete(rowData) {
      var deleteId = rowData.id;

      g_dialog.operateConfirm("确认删除选中的记录么?", {
        saveclick: function() {
          xd_ajax_post({
            url: "api/property/delete",
            paramObj: [deleteId],
            successCallBack: function(data) {
              g_dialog.operateAlert(null, "操作成功！");
              tree_get(current_selected_node_id);
            },
            failCallBack: function() {
              g_grid.refresh($("#table_div1"));
              tree_get(current_selected_node_id);
            }
          });
        }
      });
    }


    // 批量删除
    function selected_asset_list_batch_delete() {
      var dataArray = g_grid.getData($("[id=table_div1]"), { chk: true });
      if (dataArray.length == 0) {
        g_dialog.operateAlert(null, index_select_one_at_least_msg, "error");
        return false;
      }
      var assetStoreList = [];
      for (var i = 0; i < dataArray.length; i++) {
        if (list_current_data_name == "assetType") {
          assetStoreList.push({
            edId: dataArray[i].edId,
            agentId: dataArray[i].agentId,
            edTypeId: current_selected_node_id
          });
        } else {
          assetStoreList.push({
            edId: dataArray[i].edId,
            agentId: current_selected_node_id,
            edTypeId: dataArray[i].edTypeId
          });
        }
      }

      g_dialog.operateConfirm("确认删除选中的记录么?", {
        saveclick: function() {
          um_ajax_post({
            url: "siem/logcollection/delRow",
            paramObj: { assetStoreList: assetStoreList },
            successCallBack: function(data) {
              g_dialog.operateAlert(null, "操作成功！");
              tree_get(current_selected_node_id);
            }
          });
        }
      });
    }

    // 新增
    function candidate_asset_tem_init() {
      $.ajax({
        type: "GET",
        url: "module/strategy/webapp_notice_tpl.html",
        success: function(data) {
          g_dialog.dialog($(data).find("[id=asset_edit_template]"), {
            width: "800px",
            init: init,
            title: "资产信息",
            saveclick: save_click,
            autoHeight: "autoHeight"
          });
        }
      });

      function init(el) {
        g_validate.init(el);
        initSelect2Data();
        laydate.render({
          elem: '#buyDate',
          format: 'yyyy-MM-dd',
          showBottom: false
        });
      }

      function save_click(el, saveObj) {
        clearValidatorStyle($('#query_form'));
        if (!validateForm($('#query_form'))) {
          return false;
        }
        xd_ajax_get({
          url: 'api/property/checkName',
          paramObj: {
            name: saveObj.name,
          },
          successCallBack: function (data) {
            if (!data) {
              // g_dialog.operateAlert(null, '资产名称不能重复!', 'error');
              $('#name').addClass('input_validation-failed').attr('tip', '资产名称不能重复!');
              return false;
            } else {
              xd_ajax_get({
                url: 'api/property/checkIP',
                paramObj: {
                  systemId: saveObj.systemId,
                  ip: saveObj.ip
                },
                successCallBack: function (data) {
                  if (!data) {
                    // g_dialog.operateAlert(null, '同一管控域资产IP不能重复!', 'error');
                    $('#ip').addClass('input_validation-failed').attr('tip', '同一管控域资产IP不能重复!');
                    return false;
                  } else {
                    var param = [];
                    saveObj.buyDate && (saveObj.buyDate = new Date(saveObj.buyDate).getTime());
                    param.push(saveObj);
                    xd_ajax_post({
                      url: 'api/property/save',
                      paramObj: param,
                      isLoad: true,
                      successCallBack: function(data) {
                        g_dialog.operateAlert();
                        g_dialog.hide(el);
                        tree_get(current_selected_node_id);
                      }
                    });
                  }
                }
              })
            }
          }
        })
      }
    }

    // 初始化弹层下拉选择数据
    function initSelect2Data(cb) {
      // 获取操作系统
      xd_ajax_get({
        url: 'api/dic/getDicList',
        paramObj: {
          parentCode: 'PROPERTY_OS'
        },
        isLoad: false,
        successCallBack: function (data) {
          if (data.length > 0) {
            var selectData = [];
            for (var i = 0; i <  data.length; i++) {
              var text = data[i].name;
              var id = data[i].code;
              selectData.push({
                id: id,
                text: text
              });
            }
            $('#systemSelect').select2({
              data: selectData,
              placeholder: '请选择',
              allowClear: false
            });
          }
        }
      });

      // 获取管控域下拉
      xd_ajax_get({
        url: 'api/systemMonitor/getSysReginfList',
        successCallBack: function(data) {
          if (data.list.length > 0) {
            var selectData = [];
            for (var i = 0; i < data.list.length; i++) {
              var text = data.list[i].name;
              var id = data.list[i].sysId;
              selectData.push({
                id: id,
                text: text
              });
            }
            $('#systemId').select2({
              data: selectData,
              placeholder: '请选择',
              allowClear: false
            })
          }
        }
      })
    }
  });
});
